<template>
	<view class="wrap">
		<view class="header">
			<view class="header-inner">
				<view class="back-png" @click="backPage">
					<image class="header-image" src="@/static/images/arrow-left.svg" mode="aspectFill"></image>
				</view>
				<view class="title">
					箱架号维护
				</view>
				<view></view>
			</view>
		</view>

		<view class="box-list" v-if="listData.length>0">
			<view class="box-item" v-for="(item,index) in  listData" :key="index" v-if="item.type!='上传成功'">

				<uni-swipe-action class="cell-item">
					<!-- 基础用法 -->
					<uni-swipe-action-item :right-options="options" @click="itemClick($event,item)">
						<view class="cell-line">
							<view class="left">
								<view class="name">
									箱架号
								</view>
								<view class="value">
									{{item.name}}
								</view>
							</view>
							<view class="right">
								{{item.type}}
							</view>
						</view>

					</uni-swipe-action-item>
				</uni-swipe-action>


			</view>
		</view>

		<view style="margin-top: 200rpx" v-else>
			<no-Data></no-Data>
		</view>

		<view class="footer-btns">
			<u-button @click="addBox" style="width: 45%; border-radius: 12px;" type="warning" text="添加箱架号"></u-button>
			<u-button @click="dataUpload" style="width: 45%; border-radius: 12px;" type="primary"
				text="数据上传"></u-button>
		</view>
	</view>
</template>

<script>
	// 引入封装的 sqlite
	import DB from "@/utils/sqlite.js";
	import {
		getToken
	} from '@/utils/auth'
	import upload from "@/utils/upload"
	import network from "@/utils/network"
	import {
		createShelfNumber,
		uploadImg
	} from "@/api/port-area.js"
	export default {
		data() {
			return {
				listData: [],
				options: [{
					text: '编辑',
					style: {
						width: "100px",
						backgroundColor: 'white',
						color: '#3461FD',
						fontSize: '15px'
					}
				}, {
					text: '删除',
					style: {
						width: "100px",
						backgroundColor: 'white',
						color: 'red',
						fontSize: '15px'
					}
				}, ]
			}
		},
		onLoad() {
			this.createTable();
		},
		onShow() {
			this.selectTableData();
		},
		methods: {
			itemClick(e, item) {
				if (e.content.text == '编辑') {
					console.log('item', item)
					this.$tab.navigateTo('/pages/shelf-number/index?id=' + item.id);
				}
				if (e.content.text == '删除') {
					this.deleteTableData(item).then(res => {
						this.$modal.msgSuccess('移除成功')
					})
				}
			},
			// 删除表数据
			async deleteTableData(item) {
				let _this = this;
				let open = DB.isOpen();
				return new Promise((reslove, reject) => {
					if (open) {
						uni.showModal({
							title: '提示',
							content: '你确定要删除该箱架？',
							success: function(r) {
								console.log('r', r)
								if (r.confirm) {
									// 删除表 DB.deleteTableData(表名,查询条件列名,查询条件列值)
									DB.deleteTableData("tank_rack", "id", item.id)
										.then(res => {
											console.log('delete_tank_rack', res)
											// 删除表 DB.deleteTableData(表名,查询条件列名,查询条件列值)
											DB.deleteTableData("shipping_mark",
													"tank_rack_name", item.name)
												.then(res => {
													_this.selectTableData();
													reslove(true)
												})
												.catch(error => {
													console.log("删除失败", error);
													reject(error)
												});

										})
										.catch(error => {
											console.log("删除失败", error);
											reject(error)
										});

								} else {

								}

							},
						})

					} else {
						this.$modal.showToast("数据库未打开");
						reject()
					}
				})

			},
			// 创建表
			createTable() {
				let open = DB.isOpen();
				if (open) {
					// 创建表 DB.createTable(表名, 表的列)
					DB.createTable("tank_rack",
							'"id" INTEGER PRIMARY KEY AUTOINCREMENT,"name" text ,"type" text ,"content" text, "marksNoSet" text, "scanCodeMap" text,  "time" text'
						)
						.then(res => {
							// this.$modal.showToast('创建表成功')
						})
						.catch(error => {
							this.$modal.showToast('创建表失败')
						});

					//创建唛头表格
					// 创建表 DB.createTable(表名, 表的列)
					DB.createTable("shipping_mark",
							'"id" INTEGER PRIMARY KEY AUTOINCREMENT,"shipping_no" text,"tank_rack_name" text')
						.then(res => {
							// this.$modal.showToast('创建表成功')
						})
						.catch(error => {
							this.$modal.showToast('创建唛头表失败')
						});


				} else {
					this.$modal.showToast('数据库未打开')
				}
			},

			// 查询表数据
			selectTableData() {
				let open = DB.isOpen();
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					DB.selectTableData("tank_rack")
						.then(res => {
							console.log("contact表数据", res);
							this.listData = res;
						})
						.catch(error => {
							console.log("查询失败", error);
						});
				} else {
					this.$modal.showToast('数据库未打开')
				}
			},
			// 删除表数据
			clearTableData() {
				let open = DB.isOpen();
				if (open) {
					// 删除表 DB.deleteTableData(表名,查询条件列名,查询条件列值)
					DB.deleteTableData("tank_rack")
						.then(res => {
							// this.$modal.msgSuccess("清除成功");
							this.selectTableData();
						})
						.catch(error => {
							console.log("删除失败", error);
						});
				} else {
					this.$modal.showToast("数据库未打开");
				}
			},
			// 时间戳转年月日
			formatDate(data) {
				let now = new Date(data);
				var year = now.getFullYear(); //取得4位数的年份
				var month =
					now.getMonth() + 1 < 10 ?
					"0" + (now.getMonth() + 1) :
					now.getMonth() + 1;
				var date = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
				var hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
				var minute =
					now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
				var second =
					now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
				return (
					year +
					"-" +
					month +
					"-" +
					date +
					" " +
					hour +
					":" +
					minute +
					":" +
					second
				);
			},
			backPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			addBox() {
				// this.insertTableData();
				this.$tab.navigateTo('/pages/shelf-number/index');
			},
			async dataUpload() {
				let net = await network(true);
				console.log("net", net)
				if (!net || net == "none") {
					return false;
				}

				if (!this.listData.length) {
					this.$modal.msgError('暂无数据');
					return false;
				}
				for (let i = 0; i < this.listData.length; i++) {
					let item = this.listData[i];
					if (item.type == '上传成功') {
						continue;
					}


					createShelfNumber(item.name, JSON.parse(item.marksNoSet)).then(res => {
						const uid = res.data
						if (uid == null) {
							item.type = '上传失败';
							this.$modal.msgError('唛头绑定失败');
							return false;
						}

						let imgMapList = JSON.parse(item.content);
						let pAll = []
						for (let i = 0; i < imgMapList.length; i++) {
							let value = imgMapList[i];
							let p = new Promise(async (resolve, reject) => {
								let picid = await uploadImg({
									url: '/common/api/v1/attachment/upload', //仅为示例，非真实的接口地址
									filePath: value.url,
									formData: {
										bizUid: uid+'scm_portAreaManagement',
										bizType: "shelf_no_attachment"
									}
								})
								if (picid) {
									resolve(picid)
								} else {
									reject(-1)
								}
							});
							console.log("ppppp", p)
							if (p != null) {
								pAll.push(p)
							}

						}
						Promise.all(pAll).then((val) => {
							console.log('全部完成', val)
							item.type = "上传成功"
							let open = DB.isOpen();
							if (open) {
								DB.deleteTableData("tank_rack", "id", item.id)
									.then(res => {
										this.selectTableData();
										this.$modal.msgSuccess('上传成功')
									})
									.catch(error => {
										console.log("删除失败", error);
									});
							}

							// 相关操作
						}).catch((err) => {
							item.type = "上传失败"
							console.log("err", err)
						});

					}).catch(err => {
						this.$modal.msgError('服务端错误');
					})




				}
				// this.clearTableData()
				// this.$modal.showToast('数据上传成功')

			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap {
		width: 100%;
		height: calc(100vh);
		padding-top: 280rpx;
		overflow-y: scroll;
		background: var(--additional-colors-white, #FFF)
	}

	.header {
		width: 100%;
		height: 270rpx;
		flex-shrink: 0;
		border-radius: 0px 0px 60rpx 60rpx;
		background: #3461FD;
		position: fixed;
		top: 0;
		z-index: 999;
		padding-top: 120rpx;

		.header-inner {
			display: flex;
			justify-content: space-between;
			padding: 0 50rpx;
			align-items: center;

			.title {
				color: #FFF;
				text-align: center;
				font-size: 36rpx;
				font-family: PingFang SC;
				font-style: normal;
				font-weight: 800;
				line-height: 52rpx;
				letter-spacing: 0.09px;
			}

			.back-png {
				width: 100rpx;
				height: 100rpx;
				// padding: 24px;
				border-radius: 24rpx;
				text-align: center;
				line-height: 48rpx;
				background-image: url("@/static/images/back-bg.svg");
				background-size: 100rpx 100rpx;
				background-repeat: no-repeat;
				display: flex;
				justify-content: center;
				align-items: center;

				.header-image {
					width: 48rpx;
					height: 40rpx;
				}
			}
		}
	}

	.box-list {
		margin-bottom: 160rpx;
	}

	.box-item {
		width: calc(100vw - 40rpx);
		min-height: 140rpx;
		flex-shrink: 0;
		border-radius: 20rpx;
		background: #FFF;
		box-shadow: 0px 0px 50rpx 0px rgba(0, 0, 0, 0.10);
		margin: 16rpx auto;
		padding: 40rpx;

		.left {
			.name {
				color: var(--gray-3, #828282);
				text-align: left;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-style: normal;
				font-weight: 700;
				line-height: 64rpx;
			}

			.value {
				color: #1278FF;
				text-align: center;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-style: normal;
				font-weight: 600;
				line-height: normal;
			}
		}

		.right {
			color: var(--orange, #F2994A);
			text-align: center;
			font-size: 24rpx;
			font-family: PingFang SC;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}

		.cell-item {
			width: 100%;

			.cell-line {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
	}

	.footer-btns {
		position: fixed;
		width: 100vw;
		bottom: 20rpx;
		min-height: 30rpx;
		display: flex;
		justify-content: space-between;
		padding: 0 40rpx;

	}
</style>